import os
import threading
from flask import Flask
from app.utils import Route
from app.utils import Config
from flask_socketio import SocketIO
from gevent import pywsgi


def start_websocket():
    try:
        socketio.run(app, host='0.0.0.0', port=port, allow_unsafe_werkzeug=True)
    except Exception as e:
        pass


def service_start(ROOT_PATH):
    global app
    global port
    global socketio
    app = Flask(__name__, template_folder=ROOT_PATH + '/templates')
    socketio = SocketIO(app, async_mode="threading")
    app.static_folder = ROOT_PATH + "/public/static"
    # 获取配置文件
    cfg = Config.get_config()
    app.secret_key = cfg["secret_key"]
    port = cfg["port"]
    print(os.getcwd())
    # print(cfg)
    # 可以在路径内以/<参数名>的形式指定参数，默认接收到的参数类型是string
    Route.get_route(app, cfg, ROOT_PATH, ws=socketio)

    """    # 开启单独线程启动WebSocket服务
        websocket_thread = threading.Thread(target=start_websocket)
        websocket_thread.start()"""
    """
        # 使用gevent启动HTTP服务器
        server = pywsgi.WSGIServer(('0.0.0.0', cfg["port"]), app)
        server.serve_forever()"""
    start_websocket()
